<template>
  <div class="JADP-common-layout">
    <div class="JADP-common-layout-center">
      <el-row class="JADP-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="证书名称">
              <el-input
                v-model="query.certificatename"
                placeholder="请输入"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书编号">
              <el-input
                v-model="query.serialnumber"
                placeholder="请输入"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="证书等级">
              <el-select
                v-model="query.ordeanddegree"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="(item, index) in ordeanddegreeOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.id"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="资格类型">
              <JADP-TreeSelect
                v-model="query.certificateclassification"
                :options="treeData"
                placeholder="选择分类"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <template v-if="showAll">
            <el-col :span="6">
              <el-form-item label="复审时间">
                <el-date-picker
                  v-model="query.reviewtime"
                  type="daterange"
                  value-format="timestamp"
                  format="yyyy-MM-dd"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </template>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()"
                >查询</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >重置</el-button
              >
              <el-button
                type="text"
                icon="el-icon-arrow-down"
                @click="showAll = true"
                v-if="!showAll"
              >
                展开
              </el-button>
              <el-button
                type="text"
                icon="el-icon-arrow-up"
                @click="showAll = false"
                v-else
              >
                收起
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JADP-common-layout-main JADP-flex-main">
        <div class="JADP-common-head">
          <div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addOrUpdateHandle()"
              >新增
            </el-button>
            <el-button
              type="text"
              icon="el-icon-upload2"
              @click="uploadCertificate"
              >证书扫描件批量上传
            </el-button>
            <el-button type="text" icon="el-icon-download" @click="uploadForm"
              >导入
            </el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="handleBatchRemoveDel()"
              >批量删除
            </el-button>
          </div>
          <div class="JADP-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link
                icon="icon-ym icon-ym-Refresh JADP-common-head-icon"
                :underline="false"
                @click="reset()"
              />
            </el-tooltip>
            <screenfull :isContainer="true" />
            <!-- <el-tooltip effect="dark" content="列设置" placement="top">
              <el-link
                icon="icon-ym icon-ym-options JADP-common-head-icon"
                :underline="false"
              />
            </el-tooltip> -->
          </div>
        </div>
        <div class="content">
          <el-col :span="6" class="tree">
            <div class="tree-content">
              <p>资格类型</p>
              <!-- <el-button
                type="primary"
                icon="el-icon-plus"
                style="margin: 0 0 10px 20px"
                >创建分类</el-button
              > -->
              <el-tree
                :data="treeList"
                node-key="id"
                ref="tree"
                default-expand-all
                :expand-on-click-node="false"
                @node-click="treeSearch"
                :props="defaultProps"
                @node-expand="handleNodeExpand"
              >
                <template #default="{ node, data }">
                  <span class="handle-tree">
                    <el-input
                      @click.stop.native=""
                      class="add-input"
                      :value="data.label"
                      @input="a => inp(a, data)"
                      @focus="focus($event)"
                      v-if="data.text == '添加'"
                      @keydown.stop.native.enter="determine(data)"
                    ></el-input>
                    <span v-if="!data.text" style="font-size: 12px">{{
                      data.label
                    }}</span>
                    <span class="btns">
                      <el-button
                        v-if="data.text !== data.parent_id && editLog"
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click.stop="edit(data, node)"
                      ></el-button>
                      <el-button
                        v-if="data.text !== '添加'"
                        size="mini"
                        type="text"
                        icon="el-icon-plus"
                        @click.stop="testPaper(data)"
                      ></el-button>
                      <el-button
                        v-if="data.text == '添加'"
                        icon="el-icon-check"
                        size="mini"
                        type="text"
                        @click.stop="determine(data)"
                      ></el-button>
                      <el-button
                        v-if="data.id != -1"
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click.stop="removeTree(data)"
                      ></el-button>
                    </span>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-col>
          <el-col :span="18">
            <JADP-table
              v-loading="listLoading"
              :data="list"
              @sort-change="sortChange"
              has-c
              @selection-change="handleSelectionChange"
            >
              <el-table-column prop="stuname" label="学员姓名" align="left" />
              <el-table-column
                prop="certificatename"
                label="证书名称"
                align="left"
                show-overflow-tooltip
              />
              <el-table-column
                prop="serialnumber"
                label="证书编号"
                align="left"
              />

              <el-table-column
                prop="certificateclassification"
                label="资格类型"
                align="left"
              />
              <!-- <el-table-column
                label="证书等级"
                prop="ordeanddegree"
                algin="left"
              > -->
              <!-- </el-table-column> -->
              <!-- <el-table-column
                prop="certificatefixednumberofyear"
                label="证书年限"
                align="left"
              /> -->
              <!-- <el-table-column
                label="证书分类"
                prop="certificateclassification"
                algin="left"
              >
              </el-table-column> -->
              <!-- <el-table-column label="发证时间" prop="issuetime" algin="left">
              </el-table-column> -->
              <el-table-column label="复审时间" prop="reviewtime" algin="left">
              </el-table-column>

              <!-- <el-table-column label="初/复训" prop="reviewtime" algin="left">
              </el-table-column> -->
              <!-- <el-table-column
                prop="licensingagency"
                label="证书机构"
                align="left"
              />
              <el-table-column
                prop="certificatedescription"
                label="证书描述"
                align="left"
              /> -->
              <el-table-column label="操作" fixed="right" width="150">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="addOrUpdateHandle(scope.row.id)"
                    >编辑
                  </el-button>
                  <el-button
                    type="text"
                    class="JADP-table-delBtn"
                    @click="handleDel(scope.row.id)"
                    >删除
                  </el-button>
                  <el-button
                    type="text"
                    @click="addOrUpdateHandle(scope.row.id, true)"
                    >详情
                  </el-button>
                </template>
              </el-table-column>
            </JADP-table>
          </el-col>
        </div>

        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>
    <JADP-Form v-if="formVisible" ref="JADPForm" @refresh="refresh" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <ImportBox
      v-if="importBoxVisible"
      ref="importBox"
      @refresh="reset()"
      @ImportPreviewApi="ImportPreviewApi"
      @importDataApi="importDataApi"
      @TemplateDownload="TemplateDownload"
      :URL="URL"
    />
    <el-dialog
      title="证书扫描件批量上传"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-upload
        class="upload-demo"
        ref="upload"
        :headers="uploadHeaders"
        :action="uploadUrl"
        accept=".jpg, .png"
        :on-preview="handlePreview"
        :before-remove="beforeRemove"
        :auto-upload="false"
        multiple
        :file-list="fileList"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传jpg/png文件
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import request from "@/utils/request";
import JADPForm from "./Form";
import ExportBox from "./ExportBox";
import {
  testPaper,
  addTreeNode,
  deleteTreeNode,
  editTreeNode
} from "@/api/zazx/certificate";

export default {
  name: "aa",
  components: { JADPForm, ExportBox },
  data() {
    return {
      //导入属性
      importBoxVisible: false,
      URL: "certificatemanagement/Xy_ks_certificatemanagement",
      uploadHeaders: { Authorization: this.$store.getters.token },
      uploadUrl:
        process.env.VUE_APP_BASE_API + "/api/extend/FgDocument/uploaderExcel", //上传地址
      fileList: [],
      showAll: false,
      editLog: true,
      query: {
        certificatename: undefined,
        serialnumber: undefined,
        ordeanddegree: undefined,
        certificateclassification: undefined,
        licensingagency: undefined,
        certificatedescription: undefined
      },
      defaultProps: {
        children: "children",
        label: "fullName"
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatortime"
      },
      formVisible: false,
      exportBoxVisible: false,
      dialogVisible: false,
      columnList: [
        { prop: "stuname", label: "学员姓名" },
        { prop: "certificatename", label: "证书名称" },
        { prop: "serialnumber", label: "证书编号" },
        { prop: "certificateclassification", label: "资格类型" },
        { prop: "licensingagency", label: "证书机构" },
        { prop: "issuetime", label: "发证时间" },
        { prop: "reviewtime", label: "复审时间" }
      ],
      ordeanddegreeOptions: [
        { fullName: "选项一", id: "1" },
        { fullName: "选项二", id: "2" }
      ],
      certificateclassificationOptions: [
        { fullName: "选项一", id: "1" },
        { fullName: "选项二", id: "2" }
      ],
      ordeanddegreeOptions: [
        { fullName: "选项一", id: "1" },
        { fullName: "选项二", id: "2" }
      ],
      certificateclassificationOptions: [
        { fullName: "选项一", id: "1" },
        { fullName: "选项二", id: "2" }
      ],
      treeData: [],
      treeList: []
    };
  },
  computed: {},
  created() {
    this.initData();
    this.getTreeData();
    this.testPaper();
  },
  methods: {
    getTreeData() {
      this.request({
        url: "/api/xy_ks_cer_type/Xy_ks_cer_type/getTreeList",
        method: "get"
      }).then(res => {
        let topItem = {
          fullName: "资格类型",
          hasChildren: true,
          id: "-1",
          icon: "icon-ym icon-ym-tree-organization3",
          children: res.data
        };
        this.treeData = [topItem];
      });
    },

    handleNodeExpand(data, node) {
      // 处理数据可以再修改的手段
      this.$refs.tree.updateKeyChildren(
        node.data.id,
        JSON.parse(JSON.stringify(node.data.children))
      );
    },
    focus(event) {
      event.currentTarget.select();
    },

    inp(value, data) {
      this.$set(data, "label", value);
      this.$forceUpdate();
    },

    treeSearch(a) {
      this.query = {
        certificatename: undefined,
        serialnumber: undefined,
        ordeanddegree: undefined,
        certificateclassification: undefined,
        licensingagency: undefined,
        certificatedescription: undefined
      };
      a.parent_id && this.$set(this.query, "certificateclassification", a.id);
      this.initData();
    },

    async testPaper(data) {
      let res = await testPaper();
      this.treeList = res.data.list;
      let tree = {
        label: "资格类型",
        hasChildren: true,
        id: "-1",
        children: []
      };
      if (data) {
        this.editLog = false;
        if (data.id == -1) {
          this.treeList.push({
            text: "添加",
            parent_id: -1
          });
        } else {
          this.treeList.push({
            text: "添加",
            parent_id: data.id
          });
        }
      }
      this.treeList.forEach(item => {
        item.label = item.type_name;
        if (item.parent_id == "默认") item.parent_id = -1;
      });
      let parent = this.treeList.filter(item => item.parent_id == -1);
      let children = this.treeList.filter(item => item.parent_id !== -1);
      function getTreeData(parent, children) {
        parent.forEach(item => {
          children.forEach(item1 => {
            if (item1.parent_id == item.id) {
              "children" in item
                ? item.children.push(item1)
                : (item.children = [item1]);
              getTreeData([item1], children);
            }
          });
        });
      }
      getTreeData(parent, children);
      tree.children = parent;
      this.treeList = [tree];
      this.treeList = JSON.parse(JSON.stringify(this.treeList));
    },

    async edit(val, node) {
      this.$set(val, "text", "添加");
      this.$set(val, "text1", "编辑");
      this.$refs.tree.updateKeyChildren(
        val.parent_id,
        JSON.parse(JSON.stringify(node.parent.data.children))
      );
    },

    async determine(data) {
      if (!data.label) return this.$message.error("请先填写菜单名");
      data.type_name = data.label;
      if (data.text1) {
        let res = await editTreeNode(data.id, data);
        this.$message({
          type: "success",
          message: "修改成功！",
          duration: 500,
          onClose: () => {
            this.testPaper();
            this.initData();
            this.editLog = true;
          }
        });
      } else {
        const { code } = await addTreeNode(data);
        code == 200 &&
          this.$message({
            type: "success",
            message: "新建节点成功!",
            duration: 500,
            onClose: () => {
              this.testPaper();
              this.initData();
              this.editLog = true;
            }
          });
      }
    },
    removeTree(data) {
      let tip = "children" in data;
      if (tip && data.children)
        return this.$message.error("有子节点不可直接删除！");
      this.$confirm("确认删除节点吗？", "提示", { type: "waring" })
        .then(async () => {
          const { code } = await deleteTreeNode(data.id);
          code == 200 &&
            this.$message({
              type: "success",
              message: "删除成功！",
              duration: 500,
              onClose: () => {
                this.testPaper();
                this.initData();
                this.editLog = true;
              }
            });
        })
        .catch(() => {});
    },
    ImportPreviewApi(val) {
      let query = { fileName: val ,organizeId:this.$store.getters.organizeId};
      request({
        url: `/api/certificatemanagement/Xy_ks_certificatemanagement/ImportPreview`,
        method: "get",
        data: query
      })
        .then(res => {
          console.log(res, "res");
          this.$refs.importBox.list = res.data.dataRow;
          this.$refs.importBox.btnLoading = false;
          this.$refs.importBox.active++;
        })
        .catch(() => {
          this.$refs.importBox.btnLoading = false;
        });
    },
    importDataApi(val) {
      let query = { list: val,organizeId :this.$store.getters.organizeId };
      request({
        url: `/api/certificatemanagement/Xy_ks_certificatemanagement/ImportData`,
        method: "post",
        data: query
      })
        .then(res => {
          this.$refs.importBox.result = res.data;
          this.$refs.importBox.resultList = res.data.failResult;
          this.$refs.importBox.btnLoading = false;
          this.$refs.importBox.active++;
        })
        .catch(() => {
          this.$refs.importBox.btnLoading = false;
        });
    },
    TemplateDownload() {
      // request({
      //   url: `/api/certificatemanagement/Xy_ks_certificatemanagement/templateDownload`,
      //   method: "post"
      // }).then(res => {
      //   if (!res.data.url) return;
      //   window.location.href = this.define.comUrl + res.data.url;
      // });
      window.location.href =
        this.define.comUrl +
        "/v3/api/testPaperManage/Xy_ks_examination_paper/cer/templateDownload";
    },
    // 导入
    uploadForm() {
      this.importBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.importBox.init(this.columnList);
      });
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        organizeId:this.$store.getters.organizeId
      };
      let query = {};
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join();
        } else {
          query[key] = _query[key];
        }
      }
      request({
        url: `/api/certificatemanagement/Xy_ks_certificatemanagement`,
        method: "get",
        data: query
      }).then(res => {
        this.list = res.data.list;
        this.total = res.data.pagination.total;

        this.listLoading = false;
      });
    },
    handleDel(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        type: "warning"
      })
        .then(() => {
          request({
            url: `/api/certificatemanagement/Xy_ks_certificatemanagement/${id}`,
            method: "DELETE"
          }).then(res => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              }
            });
          });
        })
        .catch(() => {});
    },
    handleSelectionChange(val) {
      const res = val.map(item => item.id);
      this.multipleSelection = res;
    },
    handleBatchRemoveDel() {
      if (!this.multipleSelection.length) {
        this.$message({
          type: "error",
          message: "请选择一条数据",
          duration: 1500
        });
        return;
      }
      const ids = this.multipleSelection.join();
      this.$confirm("您确定要删除这些数据吗, 是否继续？", "提示", {
        type: "warning"
      })
        .then(() => {
          request({
            url: `/api/certificatemanagement/Xy_ks_certificatemanagement/batchRemove/${ids}`,
            method: "DELETE"
          }).then(res => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              }
            });
          });
        })
        .catch(() => {});
    },
    addOrUpdateHandle(id, isDetail) {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.JADPForm.init(id, isDetail);
      });
    },
    exportData() {
      this.exportBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList);
      });
    },
    download(data) {
      let query = { ...data, ...this.listQuery, ...this.query };
      request({
        url: `/api/certificatemanagement/Xy_ks_certificatemanagement/Actions/Export`,
        method: "GET",
        data: query
      }).then(res => {
        if (!res.data.url) return;
        window.location.href = this.define.comUrl + res.data.url;
        this.$refs.ExportBox.visible = false;
        this.exportBoxVisible = false;
      });
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatortime"
      };
      this.initData();
    },
    refresh(isrRefresh) {
      this.formVisible = false;
      if (isrRefresh) this.reset();
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined;
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatortime"
      };
      this.initData();
    },
    // 证书扫描件批量上传
    uploadCertificate() {
      this.dialogVisible = true;
    },
    //移除文件前的钩子
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    //点击查看的钩子
    handlePreview(file) {
      console.log(file);
    },
    //手动上传
    submitUpload() {
      try {
        this.$refs.upload.submit();
        this.$message.success("上传成功");
        this.dialogVisible = false;
        this.$refs.upload.clearFiles();
      } catch (error) {
        this.$message.error("上传失败，请重新上传");
      }
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .handle-tree {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding-right: 60px;
  box-sizing: border-box;
  align-items: center;
  .btns {
    display: inline-block;
    width: 20px;
  }
}
.content {
  height: 650px;
  display: flex;
  .tree {
    .tree-content {
      padding-bottom: 300px;
      width: 95%;
      margin: 0 auto;
      border: 1px solid rgb(235, 238, 248);

      p {
        line-height: 40px;
        font-size: 20px;
        border-bottom: 1px solid rgb(235, 238, 248);
        text-indent: 10px;
        margin-bottom: 30px;
      }
      ::v-deep .add-input {
        width: 200px;
        line-height: 30px;
        z-index: 50;
        .el-input__inner {
          height: 25px !important;
        }
      }
    }
  }
}
</style>
